<?php
namespace App\Services;

use App\Services\Store;
use App\Services\Goods;
use App\Services\Distribution;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Ixudra\Curl\Facades\Curl;
use Cookie;
use DB;

class Common{

	public function handelApiData($jsonData){

		$data = json_decode($jsonData, true);
		if (!$data){
			echo $jsonData;
			exit;
		}
		if ($data['code'] === 1){
			return $data['data'];
		}else{
			echo $data['msg'];
			exit;
		}
	}

	public function createGuid() {
		$charid = md5(uniqid(mt_rand(), true));
		$hyphen = chr(45);// "-"
		$uuid = substr($charid, 0, 8)
				.substr($charid, 8, 4)
				.substr($charid,12, 4)
				.substr($charid,16, 4)
				.substr($charid,20,12);
		return $uuid;
	}

	// 获取区域下拉框
    public function getAreaList($parentCode=''){

    	$host = config('admin.dataApiHost');
    	$url = $host.'/common/getAreaList?parentCode='.$parentCode;

    	$response = Curl::to($url)->get();
    	$data = $this->handelApiData($response);

    	return $data;
    }

	// 提交统计
	public function addStats($sId, $sdName, $sdValue, $sdObjId, $day=''){

		$host = config('admin.dataApiHost');
		$statsUrl = $host."/statistics/dayAdd";

		$statsData = array();
		$statsData['scKey'] = $sId;
		$statsData['sdName'] = $sdName;
		$statsData['sdValue'] = $sdValue;
		$statsData['sdObjId'] = $sdObjId;
		$statsData['day'] = $day;

		$result = Curl::to($statsUrl)->withData($statsData)->post();
		try {
		    $result = json_decode($result ,true);
			if (!isset($result['code'])){
				return $result;
			}
		    if ($result['code'] == 1){
		    	return true;
		    }else{
		    	return $result['msg'];
		    }
		} catch (Exception $e) {
		     return $e->getMessage();
		}
	}

	// 获取店铺code
	public function getScode($sId){
		$sInfo = DB::table('store')->where("sId", $sId)->first();
		return $sInfo->sCode;
	}

	// 获取全部会员数
	public function getAllMemberNum($sId){

		$host = config('admin.dataApiHost');
		$url = $host."/member/getList?mcKey={$sId}&page=1&perPage=1";
		$result = Curl::to($url)->get();
		try {
		    $result = json_decode($result ,true);
		    if ($result['code'] == 1){
		    	return $result['data']['count'];
		    }else{
		    	return $result['msg'];
		    }
		} catch (Exception $e) {
		     return $e->getMessage();
		}
	}

	// 获取库存统计信息
	public function getInventoryInfo($sId){

		$host = config('admin.dataApiHost');
		$url = $host."/storeGoodsIn/getInventory?scKey={$sId}";
		$result = Curl::to($url)->get();
		try {
		    $result = json_decode($result ,true);
		    if ($result['code'] == 1){
		    	return $result['data'];
		    }else{
		    	return $result['msg'];
		    }
		} catch (Exception $e) {
		     return $e->getMessage();
		}
	}

    // 销售商品
	public function sellGoods($sId, $auId, $sgId, $sgoSaleNum,$sgoSalePrice, $sgoMemo,
								$createUser, $muId, $sgoPayWay, $isCustomPrice=0, $accountPay=0,
								$cardPay=false, $beauticianId=false, $firstBuy=false){

		$store = DB::table('store')->where('sId', $sId)->first();
		$sInfo = $store;
		$sgoOrderId = date('YmdHis', time()).$sId.rand(10000, 99999);

		$newSgoPayWay = $sgoPayWay;
		// 额外支付
		$payMoney = 0;
		// 应该支付
		$actualShouldPay = 0;
		$priceList = (explode("|", $sgoSalePrice));
		foreach($priceList as $unitPrice){
			$actualShouldPay += $unitPrice;
		}

		if (!$cardPay || $cardPay == 'false'){
			$accountPay = 0;
		}

		// 会员卡支付
		if ($accountPay > 0){
			// 查询会员卡余额
			$muInfo = DB::table('member_users')->where('muCode', $muId)->first();
			$accountPay = $muInfo->muAccount;
			if ($accountPay >= $actualShouldPay){
				$newSgoPayWay = "会员卡";
				$accountPay = $actualShouldPay;
				$payMoney = 0;
			} else {
				$newSgoPayWay = "会员卡";
				$payMoney = $actualShouldPay - $accountPay;
			}
		}

		$postData = array();
        $postData['scKey'] = $sId;
        $postData['auId'] = $auId;
        $postData['sgId'] = $sgId;
        $postData['sgoSaleNum'] = $sgoSaleNum;
        $postData['sgoSalePrice'] = $sgoSalePrice;
        $postData['sgoMemo'] = $sgoMemo;
        $postData['sgoPayWay'] = $newSgoPayWay;
        $postData['createUser'] = $createUser;
        $postData['muId'] = $muId;
        $postData['sgoOrderId'] = $sgoOrderId;
        $postData['isCustomPrice'] = $isCustomPrice;
        $postData['auUserCode'] = $beauticianId?$beauticianId:'';

		$host = config('admin.dataApiHost');
		$url = $host."/storeGoodsOut/sell";

		$sellData = Curl::to($url)->withData($postData)->post();

		$Store = new Store();

		try {
		    $sellData = json_decode($sellData ,true);
		    if ($sellData['code'] == 1){
		    	// 会员卡不足，补充充值
		    	if ($payMoney > 0){
		    		// 当做补充充值，增加店铺金额
					$this->accountUpdate($sId, 'recharge', $sgoOrderId, '会员卡余额不足，补充充值', $createUser,
											$sInfo->sCode, $payMoney, '会员卡余额不足，补充充值', 0, $payMoney,
											'', '');
					// 当做补充充值，增加用户会员卡金额
					$this->accountUpdate($sId, 'recharge', $sgoOrderId, '会员卡余额不足，补充充值', $createUser,
											$muId, $payMoney, '会员卡余额不足，补充充值', 0, 0, '', 'recharge');
		    	}
		    	// 会员卡使用
		    	if ($accountPay > 0){
		    		// 减少店铺账户余额，当做会员卡消耗，后面进账正常计算
		    		$this->accountUpdate($sId, 'consumption', $sgoOrderId, '用户会员卡购买支出', $createUser,
											$sInfo->sCode, -1*$actualShouldPay, '', 0, -1*$actualShouldPay,
											'', '');
		    		// 减少用户会员卡余额
		    		$this->accountUpdate($sId, 'consumption', $sgoOrderId, '会员卡商品购买', $createUser,
											$muId, -1*$actualShouldPay, '', 0, 0, '', 'consumption');
		    	}

//		    	// 判断真实扣款
//		    	$payMoney = 0;
//		    	$cardConsume = 0;
//				if ($accountPay > 0){
//					$actualShouldPay = 0;
//					$priceList = (explode("|", $sgoSalePrice));
//					foreach($priceList as $unitPrice){
//						$actualShouldPay += $unitPrice;
//					}
//					if ($accountPay >= $actualShouldPay){
//						$accountPay = $actualShouldPay;
//						$payMoney = 0;
//					} else if ($accountPay){
//						$payMoney = $actualShouldPay - $accountPay;
//					} else {
//						$payMoney = $accountPay;
//					}
//
//					// 查询会员卡余额
//					$muInfo = DB::table('member_users')->where('muCode', $muId)->first();
//
//					if ($muInfo->muAccount >= $accountPay){
//						$cardConsume = $accountPay;
//					}else{
//						$cardConsume = $muInfo->muAccount;
//					}
//				}
				////////////////记录现金，支付宝，微信的收费//////////////////////
//				$actualShouldPay = 0;
//				$priceList = (explode("|", $sgoSalePrice));
//				foreach($priceList as $unitPrice){
//					$actualShouldPay += $unitPrice;
//				}
//				$actualShouldPay = $actualShouldPay - $cardConsume;

//				// 记录店铺总收入
//				if ($actualShouldPay > 0){
//					$Store->addStoreIncrement($sId, 'sTotalCashFlow', $actualShouldPay);
//				}

				$payType = '';
				if ($sgoPayWay == '现金'){
					$payType = 'incomeCash';
				} else if ($sgoPayWay == '支付宝') {
					$payType = 'incomeAlipay';
				} else if ($sgoPayWay == '微信') {
					$payType = 'incomeWx';
				} else if ($sgoPayWay == '内消'){
					$payType = 'incomeInside';
				} else if ($sgoPayWay == '收钱吧'){
					$payType = 'incomeSQB';
				} else if ($sgoPayWay == '中国工商银行'){
					$payType = 'incomeICBC';
				} else if ($sgoPayWay == '代理'){
                    $payType = 'incomeAgency';
                }

				if ($payType == 'incomeInside'){
					$Store->addStatsDay($sId, $sInfo->sCode, $payType, $sellData['data'][0]['sgoCost'], '', $sgoOrderId);
				}else{
					$Store->addStatsDay($sId, $sInfo->sCode, $payType, $actualShouldPay, '', $sgoOrderId);
				}
				////////////////记录现金，支付宝，微信的收费//////////////////////

		    	//return $result['data'];
		    	$handleIndex = 0;

		    	foreach ($sellData['data'] as $sellInfo){
		    		$handleIndex = $handleIndex + 1;

		    		// 更新用户总消费
			    	$addExpendUrl = $host."/member/addExpend";
			    	$addData = array();
			    	$addData['mcKey'] = $sId;
			    	$addData['muCode'] = $muId;
			    	$addData['addMoney'] = $sellInfo['sgoSalePrice'];

			    	Curl::to($addExpendUrl)->withData($addData)->post();

//		    		// 卡包分销
//		    		if (isset($sellInfo['sgIsTimeCard'])){
//		    			if ($sellInfo['sgIsTimeCard'] == 1){
//		    				$dpId = $sellInfo['dpId'];
//		    				$this->toToDistribution($sId, $muId, $sellInfo['sgoSalePrice'], $dpId, '', $createUser, $sellInfo['sgId'], $sellInfo['sgoSaleNum']);
//		    				continue;
//		    			}
//		    		}
					$basePrice = isset($sellInfo['basePrice'])?$sellInfo['basePrice']:false;
					// 分销完成后可以执行更改父级关系
					$isCanChangeParent = 0;
					if ($handleIndex == count($sellData['data'])){
						$isCanChangeParent = 1;
					}

					// 本次交易使用的会员卡余额
					$memberCardPay = 0;
					// 获取商品信息
					$goodsInfo = DB::table('store_goods')->where('sgId', $sellInfo['sgId'])->first();
//					if ($goodsInfo->sgIsTimeCard == 0){
//					if ($cardConsume >= $sellInfo['sgoSalePrice']){
//						$memberCardPay = $sellInfo['sgoSalePrice'];
//					} elseif ($cardConsume > 0){
//						$memberCardPay = $cardConsume;
//					}
//					$cardConsume = $cardConsume - $memberCardPay;
//					}

					// 内销
					if ($goodsInfo->sgPrice != 0 && $sellInfo['sgoSalePrice'] == 0){
						$this->accountUpdate($sId, 'goods', $sellInfo['sgoId'], '内消', $createUser,
											$sInfo->sCode, $sellInfo['sgoSalePrice'], '',
											$sellInfo['sgoCost'], $sellInfo['sgoSalePrice'] - $sellInfo['sgoCost'], '', '');
						continue;
					}

                    if (strpos(env('APP_NAME'), '巴谱店务系统') !== false){
                        // 通用分销
                        $distributionResult = $this->toCommonDistribution($sId, $muId, $sellInfo['sgoSalePrice'], $sellInfo['sgoCost'],
                                                        $goodsInfo->dpId, '', $createUser ,$sellInfo['sgId'], $sellInfo['sgoSaleNum'],
                                                        $sgoOrderId, $memberCardPay, $sellInfo['sgoId'], $beauticianId);
                    }else{
                        // 阿米分销
                        $distributionResult = $this->toAmiDistribution($sId, $muId, $basePrice, $sellInfo['sgId'], $sellInfo['sgoSaleNum'],
                        								$sellInfo['sgoSalePrice'], $sellInfo['sgoCost'], $createUser, $isCanChangeParent,
                        								$sgoOrderId, $memberCardPay, $sellInfo['sgoId'], $beauticianId, $firstBuy);
                    }

		    		if ($distributionResult !== true){
		    			$Store->channelGoodsOut($sellInfo['sgoId'], '系统错误订单取消');
		    			return '处理分销结果失败，请联系系统管理员！'.$distributionResult;
		    		}
		    	}
		    }else{
		    	return $sellData['msg'];
		    }
		} catch (Exception $e) {
		     return $e->getMessage();
		}
        Cache::put($auId.'_selling', $sgoOrderId, 10);
		return true;
	}

	// 执行阿米分销
	private function toAmiDistribution($sId, $buyUserId, $basePrice, $goodsId, $goodsNum, $money,
										$sgoCost, $createUser, $isCanChangeParent, $sgoOrderId,
										$memberCardPay, $sgoId, $beauticianId, $firstBuy){
		// 不单独计算会员卡结算，统一支出
		$memberCardPay = 0;
		// 实际支付
		$actualMoney = $money;
		if ($basePrice){
			$actualMoney = $money;
			// 分销基数金额
			$money = $basePrice;
		}

		$Store = new Store();
		$host = config('admin.dataApiHost');
		// 获取商品信息
		$goodsInfo = DB::table('store_goods')->where('sgId', $goodsId)->first();
		// 获取店铺信息
		$storeInfo = $this->getStroeInfo($sId);

		$distributionInfo = $this->getUserDistribution($sId, $buyUserId);

        ////////////美容师提成//////////////////////////////////////////////////////////////////////////////////////////////////////
        $beauticianCommissionMoney = 0;
        if ($beauticianId && $storeInfo['sBeauticianCommission'] > 0){
            $validMoney = $actualMoney;
            // 如果是卡项，减去手工费
            if ($goodsInfo->sgIsTimeCard == 1 && $goodsInfo->sgIsIncludeService == 1){
            	$validMoney = $actualMoney - ($goodsInfo->sgTimeCardNum * 20 * $goodsNum);
            }
            $beauticianCommissionMoney = $validMoney * $this->getBeauticianCommission($buyUserId, $sgoOrderId, $firstBuy);

            $tip = '卖出商品返利';
            if ($goodsInfo->sgIsTimeCard){
                $tip = '卖出卡项返利';
            }
            // 美容师提成
            $this->accountUpdate($sId, 'firstSell', $sgoId, $tip, $createUser,
            							$beauticianId, $beauticianCommissionMoney, '', 0, 0, '', '');
        }
        ////////////美容师提成//////////////////////////////////////////////////////////////////////////////////////////////////////

		// 无分销
		if (!$distributionInfo || !isset($distributionInfo['duParentUid']) || $goodsInfo->sgIsDistribution == 0){

			// 无会员卡支付
			if ($memberCardPay == 0){
				if ($goodsInfo->sgPrice != 0 && $money == 0){
					$this->accountUpdate($sId, 'goods', $sgoId, '内消', $createUser,
											$storeInfo['sCode'], $actualMoney, '',
											$sgoCost + $beauticianCommissionMoney, $actualMoney - $sgoCost - $beauticianCommissionMoney, '', '');
				} elseif ($goodsInfo->sgIsTimeCard){
					$this->accountUpdate($sId, 'goods', $sgoId, '卖出卡项流水', $createUser,
											$storeInfo['sCode'], $actualMoney, '',
											$sgoCost + $beauticianCommissionMoney, $actualMoney - $sgoCost - $beauticianCommissionMoney, '', 'cardFlow');
					$Store->addStatsDay($sId, $storeInfo['sCode'], 'timeCard', $goodsNum, '', $sgoId);
				} else {
					$this->accountUpdate($sId, 'goods', $sgoId, '卖出商品流水', $createUser,
											$storeInfo['sCode'], $actualMoney, '',
											$sgoCost + $beauticianCommissionMoney, $actualMoney - $sgoCost - $beauticianCommissionMoney, '', 'goodsFlow');
				}
			} elseif ($memberCardPay >= $actualMoney){

				if ($goodsInfo->sgPrice != 0 && $money == 0){
					// 内消走不到此逻辑
				} elseif ($goodsInfo->sgIsTimeCard){
					// 减少用户余额
					$this->accountUpdate($sId, 'goods', $sgoId, '会员卡购买卡项', $createUser,
											$buyUserId, -1*$actualMoney, '', 0, 0, '', 'cardFlow');
					// 核算用户表账户余额
					DB::table('member_users')->where('muCode', $muId)->decrement('muAccount', $actualMoney);
				} else {
					// 减少用户余额
					$this->accountUpdate($sId, 'goods', $sgoId, '会员卡购买商品', $createUser,
											$buyUserId, -1*$actualMoney, '', 0, 0, '', 'goodsFlow');
					// 核算用户表账户余额
					DB::table('member_users')->where('muCode', $muId)->decrement('muAccount', $actualMoney);
				}
				// 会员卡消耗
				$Store->addStatsDay($sId, $buyUserId, 'consumption', $actualMoney, '', $sgoId);
			} elseif ($memberCardPay > 0){
				$useMoney = $actualMoney - $memberCardPay;
				if ($goodsInfo->sgPrice != 0 && $money == 0){
					// 内消走不到此逻辑
				} elseif ($goodsInfo->sgIsTimeCard){
					$this->accountUpdate($sId, 'goods', $sgoId, '卖出卡项流水', $createUser,
											$storeInfo['sCode'], $actualMoney, '因会员卡金额不足，补充支付',
											0, $actualMoney, '', '');
					// 统计购买卡项金额
					$Store->addStatsDay($sId, $storeInfo['sCode'], 'cardFlow', $actualMoney, '');
					// 减少用户余额
					$this->accountUpdate($sId, 'goods', $sgoId, '会员卡购买卡项', $createUser,
											$buyUserId, -1*$memberCardPay, '', 0, 0, '', 'consumption');

				} else {
					$this->accountUpdate($sId, 'goods', $sgoId, '卖出商品流水', $createUser,
											$storeInfo['sCode'], $actualMoney, '因会员卡金额不足，补充支付',
											0, $actualMoney, '', '');
					// 统计购买卡项金额
					$Store->addStatsDay($sId, $storeInfo['sCode'], 'goodsFlow', $actualMoney, '');
					// 减少用户余额
					$this->accountUpdate($sId, 'goods', $sgoId, '会员卡购买商品', $createUser,
											$buyUserId, -1*$memberCardPay, '', 0, 0, '', 'consumption');
				}
			}

            // 记录美容师提成
            DB::table('store_goods_out')->where('sgoId', $sgoId)->update(['sgoCommission'=>$beauticianCommissionMoney]);

			return true;
		}

		// 分销
		if ($goodsInfo->sgIsTimeCard == 1 && $goodsInfo->sgIsIncludeService == 1){
			$money = $money - ($goodsInfo->sgTimeCardNum * 20 * $goodsNum);
		}

		$sellUserId = $distributionInfo['duParentUid'];
		$distributionInfo = $this->getUserDistribution($sId, $sellUserId);
		$parentId = $distributionInfo['duParentUid'];
		$grandId = $distributionInfo['duGrandUid'];

		$countData = array();
		$countData['goodsId'] = $goodsId;
		$countData['acKey'] = $sId;
		$countData['goodsNum'] = $goodsNum;
		$countData['payMoney'] = $money;

		$countData['selfId'] = $buyUserId;
		$countData['sellId'] = $sellUserId;
		$countData['parentId'] = $parentId;
		$countData['grandId'] = $grandId;
		$countData['alRatio'] = $goodsInfo->alRatio;
		$countData['isCanChangeParent'] = $isCanChangeParent;
//print_r($countData);exit;

		$url = $host."/agencyGoodsPrice/countMoney";

		$data = Curl::to($url)->withData($countData)->get();
        Log::info('分销结果：');
        Log::info($data);
		try {
		    $data = json_decode($data, true);
		} catch (Exception $e) {
		    return $data;
		}

		if ($data['code'] == 0){
			return $data['msg'];
		}

		$info = $data['data'];



//		if ($info['surplusMoney'] <= 0){
//			return '系统错误，分销剩余不能小于0';
//		}
        // 美容师参与提成，则该费用需要分摊
        if ($beauticianCommissionMoney > 0 && $info['shopShare']){
            if ($info['sell'] > 0 && $info['parent'] > 0 && $info['grade'] > 0){
                $denominator = $info['sell'] + $info['parent'] + $info['grade'] + $info['shopMayShareMoney'];

                $info['sell'] = $info['sell'] - ($info['sell']/$denominator*$beauticianCommissionMoney);
                $info['parent'] = $info['parent'] - ($info['parent']/$denominator*$beauticianCommissionMoney);
                $info['grade'] = $info['grade'] - ($info['grade']/$denominator*$beauticianCommissionMoney);
            } elseif ($info['sell'] > 0 && $info['parent'] > 0) {
                    $denominator = $info['sell'] + $info['parent'] + $info['shopMayShareMoney'];

                    $info['sell'] = $info['sell'] - ($info['sell']/$denominator*$beauticianCommissionMoney);
                    $info['parent'] = $info['parent'] - ($info['parent']/$denominator*$beauticianCommissionMoney);
            } elseif ($info['sell'] > 0 ) {
                    $denominator = $info['sell'] + $info['shopMayShareMoney'];

                    $info['sell'] = $info['sell'] - ($info['sell']/$denominator*$beauticianCommissionMoney);
            }
        }else{
            $beauticianCommissionMoney = 0;
        }

        // 记录美容师提成
        DB::table('store_goods_out')->where('sgoId', $sgoId)->update(['sgoCommission'=>$beauticianCommissionMoney]);

		if ($info['sell'] > 0){
			$this->accountUpdate($sId, 'goodsDis', $sgoId, '卖出商品提成', $createUser,
										$sellUserId, $info['sell'], '', 0, 0, '', '');
		}
		if ($info['parent'] > 0){
			$this->accountUpdate($sId, 'goodsDis', $sgoId, '下级卖出商品提成', $createUser,
										$parentId, $info['parent'], '', 0, 0, '', '');
		}
		if ($info['grade'] > 0){
			$this->accountUpdate($sId, 'goodsDis', $sgoId, '下级的下级卖出商品提成', $createUser,
										$grandId, $info['grade'], '', 0, 0, '', '');
		}

		$storeInfo = $this->getStroeInfo($sId);

		if ($info['surplusMoney'] > 0){
			$goodsType = 'goodsFlow';
			if ($goodsInfo->sgIsTimeCard == 1){
				$goodsType = 'cardFlow';
			}

			$disMoney = $info['sell'] + $info['parent'] + $info['grade'];
			if (!isset($info['dbActualMoney'])){
				$info['dbActualMoney'] = $actualMoney;
			}
			$this->accountUpdate($sId, 'goods', $sgoId, '卖出商品流水', $createUser,
										$storeInfo['sCode'], $actualMoney, '',
										$disMoney + $sgoCost + $beauticianCommissionMoney,
										$info['dbActualMoney'] - $disMoney - $sgoCost - $beauticianCommissionMoney, '', $goodsType);
		}

		// 记录开卡次数
		if ($goodsInfo->sgIsTimeCard){
			$Store->addStatsDay($sId, $storeInfo['sCode'], 'timeCard', $goodsNum, '', $sgoId);
		}

		/////////记录流水，成本及利润////////////////////////////////////////////

		// 记录分销日志
		$logUrl = $host."/distributionBill/add";
		$logData = array();
		$logData['dcKey'] = $sId;
		$logData['orderId'] = $sgoId;
		$logData['dbSaleMoney'] = $money;
		$logData['dbSelfMoney'] = $info['sell'];
		$logData['dbParentMoney'] = $info['parent'];
		$logData['dbGrandMoney'] = $info['grade'];
		$logData['dbSurplusMoney'] = $info['surplusMoney'];
		$logData['dbMemo'] = '';
		$logData['dbActualMoney'] = $actualMoney?$actualMoney:$money;
		$logData['uId'] = $sellUserId;
		$logData['duParentUid'] = $distributionInfo['duParentUid'];
		$logData['duGrandUid'] = $distributionInfo['duGrandUid'];
		$logData['dbObjName'] = $goodsInfo->sgName;
		$logData['dbObjId'] = $goodsInfo->sgId;
		$logData['createUser'] = $createUser;
		$logData['dbSaleNum'] = $goodsNum;
		$logData['dbCustomerUid'] = $buyUserId;
		$logData['addition'] = isset($info['addition'])?$info['addition']:[];

		Curl::to($logUrl)->withData($logData)->post();

		return true;
	}

    // 获取美容师返利比例,新用户反10%，老用户反5%
    private function getBeauticianCommission($buyUserId, $sgoOrderId, $firstBuy){

        if ($firstBuy){
            return 0.1;
        } else {
            return 0.05;
        }

        $buyHisData = DB::table('store_goods_out')
                    ->where('muId', $buyUserId)
                    ->where('sgoOrderId', '!=', $sgoOrderId)
                    ->first();
        if (empty($buyHisData)){
            return 0.1;
        }else{
            return 0.05;
        }
    }

	// 执行通用分销
	public function toCommonDistribution($sId, $buyUserId, $money, $sgoCost, $dpId, $parentId, $operationUser, $goodsId,
                                            $saleNum, $sgoOrderId, $memberCardPay, $sgoId, $beauticianId=false){

        // 不单独计算会员卡结算，统一支出
        $memberCardPay = 0;
        // 实际支付
        $actualMoney = $money;
        // 暂时不开启美容师返利
        // $beauticianId = false;

        $createUser = $operationUser;

        $Store = new Store();
        $host = config('admin.dataApiHost');
        // 获取商品信息
        $goodsInfo = DB::table('store_goods')->where('sgId', $goodsId)->first();
        // 获取店铺信息
        $storeInfo = $this->getStroeInfo($sId);

        $distributionInfo = $this->getUserDistribution($sId, $buyUserId);
        Log::info('购买人：'.$buyUserId);
        Log::info('购买人分销信息：'.json_encode($distributionInfo));

        ////////////美容师提成//////////////////////////////////////////////////////////////////////////////////////////////////////
        $beauticianCommissionMoney = 0;
        if ($beauticianId && $storeInfo['sBeauticianCommission'] > 0){

        }
        ////////////美容师提成//////////////////////////////////////////////////////////////////////////////////////////////////////

        // 无分销
        if (!$distributionInfo || !isset($distributionInfo['duParentUid']) || $goodsInfo->sgIsDistribution == 0 || !$dpId){

            // 无会员卡支付
            if ($memberCardPay == 0){
                if ($goodsInfo->sgPrice != 0 && $money == 0){
                    $this->accountUpdate($sId, 'goods', $sgoId, '内消', $createUser,
                                            $storeInfo['sCode'], $actualMoney, '',
                                            $sgoCost + $beauticianCommissionMoney, $actualMoney - $sgoCost - $beauticianCommissionMoney, '', '');
                } elseif ($goodsInfo->sgIsTimeCard){
                    $this->accountUpdate($sId, 'goods', $sgoId, '卖出卡项流水', $createUser,
                                            $storeInfo['sCode'], $actualMoney, '',
                                            $sgoCost + $beauticianCommissionMoney, $actualMoney - $sgoCost - $beauticianCommissionMoney, '', 'cardFlow');
                    $Store->addStatsDay($sId, $storeInfo['sCode'], 'timeCard', $goodsNum, '', $sgoId);
                } else {
                    $this->accountUpdate($sId, 'goods', $sgoId, '卖出商品流水', $createUser,
                                            $storeInfo['sCode'], $actualMoney, '',
                                            $sgoCost + $beauticianCommissionMoney, $actualMoney - $sgoCost - $beauticianCommissionMoney, '', 'goodsFlow');
                }
            } elseif ($memberCardPay >= $actualMoney){

                if ($goodsInfo->sgPrice != 0 && $money == 0){
                    // 内消走不到此逻辑
                } elseif ($goodsInfo->sgIsTimeCard){
                    // 减少用户余额
                    $this->accountUpdate($sId, 'goods', $sgoId, '会员卡购买卡项', $createUser,
                                            $buyUserId, -1*$actualMoney, '', 0, 0, '', 'cardFlow');
                    // 核算用户表账户余额
                    DB::table('member_users')->where('muCode', $buyUserId)->decrement('muAccount', $actualMoney);
                } else {
                    // 减少用户余额
                    $this->accountUpdate($sId, 'goods', $sgoId, '会员卡购买商品', $createUser,
                                            $buyUserId, -1*$actualMoney, '', 0, 0, '', 'goodsFlow');
                    // 核算用户表账户余额
                    DB::table('member_users')->where('muCode', $buyUserId)->decrement('muAccount', $actualMoney);
                }
                // 会员卡消耗
                $Store->addStatsDay($sId, $buyUserId, 'consumption', $actualMoney, '', $sgoId);
            } elseif ($memberCardPay > 0){
                $useMoney = $actualMoney - $memberCardPay;
                if ($goodsInfo->sgPrice != 0 && $money == 0){
                    // 内消走不到此逻辑
                } elseif ($goodsInfo->sgIsTimeCard){
                    $this->accountUpdate($sId, 'goods', $sgoId, '卖出卡项流水', $createUser,
                                            $storeInfo['sCode'], $actualMoney, '因会员卡金额不足，补充支付',
                                            0, $actualMoney, '', '');
                    // 统计购买卡项金额
                    $Store->addStatsDay($sId, $storeInfo['sCode'], 'cardFlow', $actualMoney, '');
                    // 减少用户余额
                    $this->accountUpdate($sId, 'goods', $sgoId, '会员卡购买卡项', $createUser,
                                            $buyUserId, -1*$memberCardPay, '', 0, 0, '', 'consumption');

                } else {
                    $this->accountUpdate($sId, 'goods', $sgoId, '卖出商品流水', $createUser,
                                            $storeInfo['sCode'], $actualMoney, '因会员卡金额不足，补充支付',
                                            0, $actualMoney, '', '');
                    // 统计购买卡项金额
                    $Store->addStatsDay($sId, $storeInfo['sCode'], 'goodsFlow', $actualMoney, '');
                    // 减少用户余额
                    $this->accountUpdate($sId, 'goods', $sgoId, '会员卡购买商品', $createUser,
                                            $buyUserId, -1*$memberCardPay, '', 0, 0, '', 'consumption');
                }
            }

            // 记录美容师提成
            DB::table('store_goods_out')->where('sgoId', $sgoId)->update(['sgoCommission'=>$beauticianCommissionMoney]);

            return true;
        }

        // 分销,可能需要扣除服务费在进行分销
        if ($goodsInfo->sgIsTimeCard == 1 && $goodsInfo->sgIsIncludeService == 1){
            //$money = $money - ($goodsInfo->sgTimeCardNum * 20 * $goodsNum);
        }

        $sellUserId = $distributionInfo['duParentUid'];
        $distributionInfoReal = $this->getUserDistribution($sId, $sellUserId);
        $parentId = $distributionInfoReal['duParentUid'];
        $grandId = $distributionInfoReal['duGrandUid'];

        Log::info('分销父id：');
        Log::info($sellUserId);
        // $uId = $buyUserId;

        $disUrl = $host."/distributionUsers/distribution";
        $disData = array();
        $disData['dcKey'] = $sId;
        $disData['customerUid'] = $buyUserId;
        $disData['uId'] = $sellUserId;
        $disData['money'] = $money;
        $disData['dpId'] = $dpId;
        $disData['parentId'] = '';
        $disData['dbMemo'] = '';
        $disData['orderId'] = $sgoId;
        $disData['saleNum'] = $saleNum;
        $disData['operationUser'] = $operationUser;
        $disData['goodsId'] = $goodsInfo->sgId;
        $disData['goodsName'] = $goodsInfo->sgName;

        $disResult = Curl::to($disUrl)->withData($disData)->post();

        Log::info('分销结果：');
        Log::info($disResult);
        try {
            $disInfo = json_decode($disResult, true);
            $disInfo = $disInfo['data'];
        } catch (Exception $e) {
            return $disResult;
        }

        $info['sell'] = $disInfo['dbSelfMoney'];
        $info['parent'] = $disInfo['dbParentMoney'];
        $info['grade'] = $disInfo['dbGrandMoney'];
        $info['surplusMoney'] = $disInfo['dbSurplusMoney'];

//		if ($info['surplusMoney'] <= 0){
//			return '系统错误，分销剩余不能小于0';
//		}

        // // 美容师参与提成，则该费用需要分摊
        // if ($beauticianCommissionMoney > 0 && $info['shopShare']){
        //     if ($info['sell'] > 0 && $info['parent'] > 0 && $info['grade'] > 0){
        //         $denominator = $info['sell'] + $info['parent'] + $info['grade'] + $info['shopMayShareMoney'];

        //         $info['sell'] = $info['sell'] - ($info['sell']/$denominator*$beauticianCommissionMoney);
        //         $info['parent'] = $info['parent'] - ($info['parent']/$denominator*$beauticianCommissionMoney);
        //         $info['grade'] = $info['grade'] - ($info['grade']/$denominator*$beauticianCommissionMoney);
        //     } elseif ($info['sell'] > 0 && $info['parent'] > 0) {
        //             $denominator = $info['sell'] + $info['parent'] + $info['shopMayShareMoney'];

        //             $info['sell'] = $info['sell'] - ($info['sell']/$denominator*$beauticianCommissionMoney);
        //             $info['parent'] = $info['parent'] - ($info['parent']/$denominator*$beauticianCommissionMoney);
        //     } elseif ($info['sell'] > 0 ) {
        //             $denominator = $info['sell'] + $info['shopMayShareMoney'];

        //             $info['sell'] = $info['sell'] - ($info['sell']/$denominator*$beauticianCommissionMoney);
        //     }
        // }else{
        //     $beauticianCommissionMoney = 0;
        // }

        // 记录美容师提成
        DB::table('store_goods_out')->where('sgoId', $sgoId)->update(['sgoCommission'=>$beauticianCommissionMoney]);

        if ($info['sell'] > 0){
            $this->accountUpdate($sId, 'goodsDis', $sgoId, '卖出商品提成', $createUser,
                                        $sellUserId, $info['sell'], '', 0, 0, '', '');
        }
        if ($info['parent'] > 0){
            $this->accountUpdate($sId, 'goodsDis', $sgoId, '下级卖出商品提成', $createUser,
                                        $parentId, $info['parent'], '', 0, 0, '', '');
        }
        if ($info['grade'] > 0){
            $this->accountUpdate($sId, 'goodsDis', $sgoId, '下级的下级卖出商品提成', $createUser,
                                        $grandId, $info['grade'], '', 0, 0, '', '');
        }

        if ($info['surplusMoney'] > 0){
            $goodsType = 'goodsFlow';
            if ($goodsInfo->sgIsTimeCard == 1){
                $goodsType = 'cardFlow';
            }

            $disMoney = $info['sell'] + $info['parent'] + $info['grade'];
            if (!isset($info['dbActualMoney'])){
                $info['dbActualMoney'] = $actualMoney;
            }
            $this->accountUpdate($sId, 'goods', $sgoId, '卖出商品流水', $createUser,
                                        $storeInfo['sCode'], $actualMoney, '',
                                        $disMoney + $sgoCost + $beauticianCommissionMoney,
                                        $info['dbActualMoney'] - $disMoney - $sgoCost - $beauticianCommissionMoney, '', $goodsType);
        }

        // 记录开卡次数
        if ($goodsInfo->sgIsTimeCard){
            $Store->addStatsDay($sId, $storeInfo['sCode'], 'timeCard', $goodsNum, '', $sgoId);
        }

        return true;
	}

	// 获取分销关系
    public function getUserDistribution($sId, $userId){

		$host = config('admin.dataApiHost');
		$url = $host."/distributionUsers/getUserInfo?dcKey={$sId}&uId={$userId}";

		$data = Curl::to($url)->get();
		// 无关系会返回{}
		$data = json_decode($data, true);
		if (isset($data['data'])){
			$info = $data['data'];
			return $info;
		}else{
			return false;
		}
    }

    // 获取用户信息
    public function getUserInfoByUid($sId, $userId){

		$host = config('admin.dataApiHost');
		$url = $host."/member/getUserInfoByUserId?mcKey={$sId}&userId={$userId}";

		$data = Curl::to($url)->get();

		$data = json_decode($data, true);
		$info = $data['data'];

		return $info;
    }

     // 根据id获取用户身份等级
    public function getDistributionLevel($sId, $userId){

    	// 获取会员id
		$host = config('admin.dataApiHost');
		$url = $host."/member/getUserInfoByUserId?mcKey={$sId}&userId={$userId}";

		$data = Curl::to($url)->get();

		$data = json_decode($data, true);
		if (isset($data['data'])){
			$info = $data['data'];
			if (isset($info['alId'])){
				return $info['alId'];
			}
		}

		// 获取店员id
		$info = DB::table('admin_users')->where('sId', $sId)->where('auCode', $userId)->first();
		if (isset($info->alId)){
			return $info->alId;
		}

		$levelInfo = DB::table('agency_level')->where('alLevel', 1)->where('acId', $sId)->first();
		// 都没有则为初级用户
		return $levelInfo->alId;
    }

    // 根据id获取用户身份等级
    public function getStroeInfo($sId){

		$host = config('admin.dataApiHost');
		$url = $host."/store/get/{$sId}";

		$data = Curl::to($url)->get();
		$data = json_decode($data, true);
		$info = $data['data'];

		return $info;
    }

    // 获取商品价格-用户
	public function getGoodsPrice($sId, $sgId, $muCode){

		if ($sgId){
			$sgInfo = DB::table('store_goods')->where('sgId', $sgId)->first();
			if ($sgInfo->sgIsTimeCard){
				$Goods = new Goods();
				return $Goods->getCardPrice($sId, $sgId, $muCode);
			}

			if ($muCode){
				$sql = "SELECT CASE WHEN sg.sgIsTimeCard = 1 THEN sg.sgPrice WHEN agp.goodsPrice IS NULL THEN sg.sgPrice ELSE agp.goodsPrice END AS goodsPrice, sg.sgId AS goodsId, sg.sgName
FROM store_goods AS sg
LEFT JOIN agency_goods_price AS agp ON agp.goodsId = sg.sgId AND sg.sId = agp.acId
LEFT JOIN agency_level AS al ON agp.acId = al.acId AND agp.alLevel = al.alLevel
LEFT JOIN member_users AS mu ON mu.alId = al.alId
WHERE sg.sId = ? AND sg.sgId = ? AND mu.muCode = ? ";
			}else{
				$sql = "SELECT CASE WHEN sg.sgIsTimeCard = 1 THEN sg.sgPrice WHEN agp.goodsPrice IS NULL THEN sg.sgPrice ELSE MAX(agp.goodsPrice) END AS goodsPrice, sg.sgId AS goodsId, sg.sgName
FROM store_goods AS sg
LEFT JOIN agency_goods_price AS agp ON agp.goodsId = sg.sgId AND sg.sId = agp.acId
WHERE sg.sId = ? AND sg.sgId = ? ";
			}

			$price = DB::select($sql, [$sId, $sgId, $muCode]);
			if (count($price) == 0){
				return false;
			}

			$price = $price[0]->goodsPrice;

			return $price;
		}else{
			if ($muCode){
				$sql = "SELECT CASE WHEN sg.sgIsTimeCard = 1 THEN sg.sgPrice WHEN agp.goodsPrice IS NULL THEN sg.sgPrice ELSE agp.goodsPrice END AS goodsPrice, sg.sgId AS goodsId, sg.sgName, sg.sgIsTimeCard
FROM store_goods AS sg
LEFT JOIN agency_goods_price AS agp ON agp.goodsId = sg.sgId AND sg.sId = agp.acId
LEFT JOIN agency_level AS al ON agp.acId = al.acId AND agp.alLevel = al.alLevel
LEFT JOIN member_users AS mu ON mu.alId = al.alId AND mu.muCode = ?
WHERE sg.sId = ?  AND (mu.alId IS NOT NULL OR sg.sgIsTimeCard = 1)";
				$priceList = DB::select($sql, [$muCode, $sId]);
			}else{
				$sql = "SELECT CASE WHEN sg.sgIsTimeCard = 1 THEN sg.sgPrice WHEN agp.goodsPrice IS NULL THEN sg.sgPrice ELSE MAX(agp.goodsPrice) END AS goodsPrice, sg.sgId AS goodsId, sg.sgName
FROM store_goods AS sg
LEFT JOIN agency_goods_price AS agp ON agp.goodsId = sg.sgId AND sg.sId = agp.acId
WHERE sg.sId = ?
GROUP BY sg.sgId ";
				$priceList = DB::select($sql, [$sId, $muCode]);
			}

			if (empty($priceList)){
				return $this->getGoodsPrice($sId, false, false);
			}
			if ($muCode){
				$Goods = new Goods();
				for($i=0;$i<count($priceList);$i++){
					if ($priceList[$i]->sgIsTimeCard){
						$priceList[$i]->goodsPrice = $Goods->getCardPrice($sId, $priceList[$i]->goodsId, $muCode);
					}
				}
			}

			return $priceList;
		}
	}

	// 获取商品价格-店员
	public function getGoodsPriceForClerk($sId, $sgId, $auCode){

		if ($sgId){
			if ($auCode){
				$sql = "SELECT agp.goodsPrice
	FROM admin_users AS au
	LEFT JOIN agency_level AS al ON au.alId = al.alId
	LEFT JOIN agency_goods_price AS agp ON au.sId = agp.acId AND al.alLevel = agp.alLevel
	LEFT JOIN store_goods AS sg ON sg.sgId = agp.goodsId AND sg.scId = au.sId
	WHERE au.sId = ? AND sg.sgId = ? AND au.auCode = ? ";
			}else{
				$sql = "SELECT MAX(agp.goodsPrice) AS goodsPrice
	FROM agency_goods_price AS agp
	WHERE agp.acId = ? AND agp.goodsId = ?";
			}

			$price = DB::select($sql, [$sId, $sgId, $auCode]);
			if (count($price) == 0){
				return false;
			}

			$price = $price[0]->goodsPrice;

			return $price;
		}else{
			$sql = "SELECT agp.goodsPrice, agp.goodsId, sg.sgName
	FROM admin_users AS au
	LEFT JOIN agency_level AS al ON au.alId = al.alId
	LEFT JOIN agency_goods_price AS agp ON au.sId = agp.acId AND al.alLevel = agp.alLevel
	LEFT JOIN store_goods AS sg ON sg.sgId = agp.goodsId AND sg.scId = au.sId
	WHERE au.sId = ? AND au.auCode = ? ";
			$priceList = DB::select($sql, [$sId, $auCode]);

			return $priceList;
		}
	}

	// 判断id是店员还是会员
	public function judgeCode($code, $isGetInfo=false){

		$auInfo = DB::table('admin_users')->where('auCode', $code)->first();
		if ($auInfo){
			if ($isGetInfo){
				return $auInfo;
			}
			return 'au';
		}
		$muInfo = DB::table('member_users')->where('muCode', $code)->first();
		if ($muInfo){
			if ($isGetInfo){
				return $muInfo;
			}
			return 'mu';
		}
		return false;
	}

	// 传入用户码获取商品价格
	public function getPrice($sId, $sgId, $code){
		$codeBelong = $this->judgeCode($code);
		if ($codeBelong == 'au'){
			return $this->getGoodsPriceForClerk($sId, $sgId, $code);
		}else if ($codeBelong == 'mu'){
			return $this->getGoodsPrice($sId, $sgId, $code);
		}
		return false;
	}

	// 获取店员下拉框
    public function getReferrerSelect($sId){

		$userModel = config('admin.database.users_model');


        $userM = new $userModel();
		$userList = $userM->where('sId', $sId)->get();

		$selectData = array();
		foreach($userList as $info){
			$selectData[$info['auCode']] = $info['name'];
		}

//      $host = config('admin.dataApiHost');
//      $sId = Admin::user()->sId;
//      $url = $host . "/member/getList?mcKey={$sId}&page=1&perPage=1000";
//      $rst = Curl::to($url)->get();
//      $user = json_decode($rst, true);
//      if(!empty($user['data']['data'])){
//          $list = $user['data']['data'];
//          foreach($list as $info){
//              $selectData[$info['muCode']] = $info['muRealName'];
//          }
//      }

		return $selectData;
	}

	public function getAssetsTypeSelect($scId){

		$typeList = DB::table('store_params')
						->where('scId', $scId)
						->where('spType', 'assetType')
						->orderBy('spSort', 'DESC')
						->get();

		$selectArray = array();
		foreach($typeList as $typeInfo){
			$selectArray[$typeInfo->spId] = $typeInfo->spKey;
		}

		return $selectArray;
	}

	// 获取商品最低价
	public function getAmiBottomPrice($sId, $muCode, $sgId=false){

		$disInfo = $this->getUserDistribution($sId, $muCode);
		if (!$disInfo){
			return $this->getMinPrice($sId, $sgId);
		}else{
			if ($disInfo['duParentUid']){
				$duParentUid = $disInfo['duParentUid'];
				$selfInfo = $this->judgeCode($muCode, true);
				$selfLevel = DB::table('agency_level')->where('alId', $selfInfo->alId)->value('alLevel');
				$parentInfo = $this->judgeCode($duParentUid, true);
				$parentLevel = DB::table('agency_level')->where('alId', $parentInfo->alId)->value('alLevel');
				// 父级等级低于自身，则用自身价格
				if ($selfLevel > $parentLevel){
					return $this->getPrice($sId, $sgId, $muCode);
				}
				return $this->getPrice($sId, $sgId, $duParentUid);
			}else{
				return $this->getMinPrice($sId, $sgId);
			}
		}
	}

	// 获取商品最低价
	private function getMinPrice($sId, $sgId=false){
		if ($sgId){
			$minPrice = DB::table('agency_goods_price')
							->selectRaw('MIN(goodsPrice) AS minPrice')
							->where('goodsId', $sgId)
							->where('acId', $sId)
							->value('minPrice');
			if (empty($minPrice)){
				return 0;
			}
			return $minPrice;
		}else{
			$minPriceList = DB::table('agency_goods_price')
							->selectRaw('goodsId, MIN(goodsPrice) AS minPrice')
							->where('acId', $sId)
							->groupBy('goodsId')
							->get();
			return $minPriceList;
		}
	}

	// 获取账户金额
    public function getAccount($sId, $userCode){

    	$money = DB::table("wallet_account")
    				->where('wcusId', $sId)
    				->where('uId', $userCode)
    				->value('waMoney');

    	if (empty($money)){
    		$money = 0;
    	}

    	return $money;
    }

    // 获取店铺固定资产
    public function getAccountAssets($sId, $assetsType = 1){

		if ($assetsType != 3){
			$assetsWorth = DB::table('store_assets')
					->select(DB::raw('IFNULL(SUM(saWorth),0) AS assetsWorth'))
					->where('sId', $sId)
					->where('saOwnStatus', $assetsType)
					->value('assetsWorth');
		}else{
			$assetsWorth = DB::table('store_assets')
					->select(DB::raw('IFNULL(SUM(saRent),0) AS assetsWorth'))
					->where('sId', $sId)
					->where('saOwnStatus', $assetsType)
					->value('assetsWorth');
		}

    	return $assetsWorth;
    }

    // 商店数据自增
    public function storeStatsIncrement($sId, $columnName, $value){

    	DB::table('store')->where('sId', $sId)->increment($columnName, $value);
    }

    // 获取店员下拉框
    public function getClerkSelect($sId){

		$userModel = config('admin.database.users_model');

        $userM = new $userModel();
		$userList = $userM->where('sId', $sId)->get();
//		print_r($userList);exit;
		$selectData = array();
		foreach($userList as $info){
			$selectData[$info['auCode']] = $info['name'];
		}

//      $host = config('admin.dataApiHost');
//      $sId = Admin::user()->sId;
//      $url = $host . "/member/getList?mcKey={$sId}&page=1&perPage=1000";
//      $rst = Curl::to($url)->get();
//      $user = json_decode($rst, true);
//      if(!empty($user['data']['data'])){
//          $list = $user['data']['data'];
//          foreach($list as $info){
//              $selectData[$info['muCode']] = $info['muRealName'];
//          }
//      }

		return $selectData;
	}

	//PHP 计算两个时间戳之间相差的时间
	//功能：计算两个时间戳之间相差的日时分秒
	//$begin_time  开始时间戳
	//$end_time 结束时间戳
	public function timediff($begin_time, $end_time)
	{
	    if($begin_time < $end_time){
	        $starttime = $begin_time;
	        $endtime = $end_time;
	    }else{
	        $starttime = $end_time;
	        $endtime = $begin_time;
	    }
	    //计算天数
	    $timediff = $endtime-$starttime;
	    $days = intval($timediff/86400);
	    //计算小时数
	    $remain = $timediff%86400;
	    $hours = intval($remain/3600);
	    //计算分钟数
	    $remain = $remain%3600;
	    $mins = intval($remain/60);
	    //计算秒数
	    $secs = $remain%60;
	    $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
	    return $res;
	}

	// 绑定分销关系
	public function boundRelation($sId, $uId, $parentId, $operationUser){

		// 绑定关系
		$host = config('admin.dataApiHost');
		$url = $host.'/distributionUsers/boundRelation';
		$data = array();
		$data['dcKey'] = $sId;
		$data['uId'] = $uId;
		$data['parentId'] = $parentId;
		$data['operationUser'] = $operationUser;

		$response = Curl::to($url)->withData($data)->post();
	}

	// 获取统计信息
	public function getStoreStatsList($sId, $typeName, $page=1, $perPage=20){

    	$sInfo = DB::table('store')->where("sId", $sId)->first();

		$sql = "SELECT t1.day AS incomeDay, incomeCash, incomeAlipay, incomeWx
FROM
(
SELECT s.*, IFNULL(sd.sdValue,0) AS incomeCash
FROM sys_day AS s LEFT JOIN stats_day AS sd ON s.day = sd.sdDay AND sd.sdName = 'incomeCash' AND sd.sdObjId = ?
WHERE s.day < NOW()
) AS t1
LEFT JOIN
(
SELECT s.*, IFNULL(sd.sdValue,0) AS incomeAlipay
FROM sys_day AS s LEFT JOIN stats_day AS sd ON s.day = sd.sdDay AND sd.sdName = 'incomeAlipay' AND sd.sdObjId = ?
WHERE s.day < NOW()
) AS t2 ON t1.day = t2.day
LEFT JOIN
(
SELECT s.*, IFNULL(sd.sdValue,0) AS incomeWx
FROM sys_day AS s LEFT JOIN stats_day AS sd ON s.day = sd.sdDay AND sd.sdName = 'incomeWx' AND sd.sdObjId = ?
WHERE s.day < NOW()
) AS t3 ON t1.day = t3.day
ORDER BY t1.day DESC
LIMIT ?, ?
";

		$list = DB::select($sql, [$sInfo->sCode, $sInfo->sCode, $sInfo->sCode, ($page-1)*$perPage, $perPage]);

		return $list;
	}

	// 获取用户信息
	public function getUserInfoWithCache($sId, $userCode, $cache=true){

		if (Cache::has($userCode)) {
		    $userInfo = Cache::get($userCode);
		    return $userInfo;
		}

		$sql = "SELECT t.*, al.alName
FROM
(
SELECT mu.muNickName AS userName, mu.muCode AS userCode, mu.alId, mu.mcId AS sId
FROM member_users AS mu
WHERE mu.mcId = ? AND muCode = ?
UNION
SELECT au.name AS userName1, au.auCode AS userCode1,au.alId, au.sId
FROM admin_users AS au
WHERE au.sId = ? AND auCode = ?
) AS t
LEFT JOIN agency_level AS al ON al.alId = t.alId";

		$list = DB::select($sql, [$sId, $userCode, $sId, $userCode]);

		if ($cache){
			Cache::put($userCode, $list[0], 60);
		}

		return $list[0];
	}

	// 获取产品售出列表
	public function getSaleDayList($sId, $statsDay=false, $auCode=false){

		$sql = "SELECT sgo.*, sg.sgName, mu.muNickName
FROM store_goods_out AS sgo
LEFT JOIN store_goods AS sg ON sgo.sgId = sg.sgId
LEFT JOIN admin_users AS au ON sgo.createUser = au.`name` AND sgo.sId = au.sId
LEFT JOIN member_users AS mu ON sgo.muId = mu.muCode
WHERE sgo.sId = ?";
		if ($statsDay){
			$sql = $sql." AND DATE_FORMAT(sgo.createTime,'%Y-%m-%d') = ? ";
		}
		if ($auCode){
			$sql = $sql." AND au.auCode = ? ";
		}
		if ($statsDay){
			$sql = $sql." ORDER BY sgo.sgoId ";
		}else{
			$sql = $sql." ORDER BY sgo.sgoId DESC";
		}

		$list = DB::select($sql, [$sId, $statsDay, $auCode]);

		return $list;
	}

	// 获取服务列表
	public function getServiceDayList($sId, $statsDay=false, $auCode=false, $sclId=false){

		$sql = "SELECT scl.*, au.name, mu.muNickName, sg.sgServiceMoney, sg.sgName
FROM store_cards_log AS scl
LEFT JOIN admin_users AS au ON scl.auCode = au.auCode AND scl.sId = au.sId
LEFT JOIN member_users AS mu ON scl.muCode = mu.muCode AND mu.mcId = scl.sId
LEFT JOIN store_goods AS sg ON scl.sgId = sg.sgId
WHERE scl.sId = ?";
		if ($sclId){
			$sql = $sql." AND scl.sclId = ? ";
			$list = DB::select($sql, [$sId, $sclId]);
			return $list[0];
		}
		if ($statsDay){
			$sql = $sql." AND DATE_FORMAT(scl.createTime,'%Y-%m-%d') = ? ";
		}
		if ($auCode){
			$sql = $sql." AND au.auCode = ? ";
		}
		if ($statsDay){
			$sql = $sql." ORDER BY scl.sclId ";
		}else{
			$sql = $sql." ORDER BY scl.sclId DESC";
		}

		$list = DB::select($sql, [$sId, $statsDay, $auCode]);

		return $list;
	}

	// 获取钱包余额
	public function getWalletMoney($sId, $uId){

		$host = config('admin.dataApiHost');
		$accountUrl = $host."/wallet/getAccountInfo?wcusKey={$sId}&uId={$uId}";
		$data = Curl::to($accountUrl)->get();

		try {
		     $data = json_decode($data, true);
		     if ($data['code'] == 0){
		     	$accountMoney = $data['msg'];
		     }else{
		     	$accountMoney = $data['data']['waMoney'];
		     }
		} catch (Exception $e) {
		     $accountMoney = '获取账户信息错误！';
		}
		return $accountMoney;
	}

	// 账目更改
	public function accountUpdate($wcusKey, $wtObj, $wtObjId, $wtAbstract, $createUser,
										$uId, $wtChangedMoney, $wtMemo, $wtCost, $wtProfit,
										$wtOrderCode, $updateType){

		$Store = new Store();

		// 更改钱包流水
		$Store->addWalletTrade($wcusKey, $wtObj, $wtObjId, $wtAbstract, $createUser, $uId,
									$wtChangedMoney, $wtMemo, $wtCost, $wtProfit, $wtOrderCode);

		// 统计流水
		if ($wtCost != 0 || $wtProfit != 0){
		  $Store->addStatsDay($wcusKey, $uId, 'flowAccount', $wtChangedMoney, $wtMemo, $wtObjId);
		}

		// 记录店铺总收入
		if ($wtChangedMoney > 0 && ($wtCost != 0 || $wtProfit != 0)){
			$Store->addStoreIncrement($wcusKey, 'sTotalCashFlow', $wtChangedMoney);
		}

		// 统计成本
		if ($wtCost != 0){
			$Store->addStatsDay($wcusKey, $uId, 'cost', $wtCost, $wtMemo, $wtObjId);
		}

		// 统计利润
		if ($wtProfit != 0){
			$Store->addStatsDay($wcusKey, $uId, 'profit', $wtProfit, $wtMemo, $wtObjId);
			// 记录店铺总利润
	    	$Store->addStoreIncrement($wcusKey, 'sTotalProfit', $wtProfit);
		}

		// 分卡项和商品添加流水
		if ($updateType == 'cardFlow' || $updateType == 'goodsFlow'){
			$Store->addStatsDay($wcusKey, $uId, $updateType, $wtChangedMoney, $wtMemo, $wtObjId);
		}

		// 会员卡消耗和充值
		if ($updateType == 'consumption' || $updateType == 'recharge'){
			$sInfo = DB::table('store')->where("sId", $wcusKey)->first();
			$Store->addStatsDay($wcusKey, $sInfo->sCode, $updateType, abs($wtChangedMoney), $wtMemo, $wtObjId);
		}

		if ($wtCost == 0 && $wtProfit == 0){
			// 核算用户表账户余额
			DB::table('member_users')->where('mcId', $wcusKey)->where('muCode', $uId)->increment('muAccount', $wtChangedMoney);
		}
	}

	public function setMoreStoreLogin($request){
        $userModel = config('admin.database.users_model');
        $userM = new $userModel();
        $userInfo = $userM->where('auCode', $request->admin_code)->first();
        if($userInfo){
            Auth::guard('admin')->loginUsingId($userInfo->id, false);
            Cookie::queue('shop_name',$request->shop_name);
        }
    }

    // 获取账本列表
    public function getWalletList($sId, $uId, $page=1, $perPage=20){

    	$host = config('admin.dataApiHost');
    	$url = $host."/wallet/getUserTrade?page={$page}&perPage={$perPage}&wcusKey={$sId}&uId={$uId}";

		$response = Curl::to($url)->get();
		$data = $this->handelApiData($response);
        $Distribution = new Distribution();
        $Common = new Common();
		for ($i=0;$i<count($data['data']);$i++){
			if ($data['data'][$i]['wtObj'] == 'shareBonus'){           // 分红
				$slInfo = DB::table('share_log')
							->selectRaw(' *, share_bonus.sbShareMoney+share_bonus.sbTransferMoney AS totalProfit')
							->leftJoin('share_bonus', function ($join) {
						        $join->on('share_log.sbMonth', '=', 'share_bonus.sbMonth')
						        	 ->on('share_log.sId', '=', 'share_bonus.sId');
						    })
							->where('share_log.slId', $data['data'][$i]['wtObjId'])
							->first();
				$data['data'][$i]['tradeInfo'] = $slInfo;
				$data['data'][$i]['tradeColumn'] = '详细';
			} elseif ($data['data'][$i]['wtObj'] == 'getSettleTip'){   // 获取服务费

				$serviceInfo = $Common->getServiceDayList($data['data'][$i]['wcusId'], false, false, $data['data'][$i]['wtObjId']);
				$data['data'][$i]['tradeInfo'] = $serviceInfo;
				$data['data'][$i]['tradeColumn'] = '详细';
			} elseif ($data['data'][$i]['wtObj'] == 'goods') {
				$sgoInfo = DB::table('store_goods_out')
								->leftJoin('store_goods', 'store_goods_out.sgId', '=', 'store_goods.sgId')
								->leftJoin('member_users', 'store_goods_out.muId', '=', 'member_users.muCode')
                                ->leftJoin('admin_users', 'admin_users.auCode', '=', 'store_goods_out.auUserCode')
								->where('sgoId', $data['data'][$i]['wtObjId'])
								->first();

				$disInfo = $Distribution->getOrderDis($sId, $data['data'][$i]['wtObjId']);

				$data['data'][$i]['sgoInfo'] = $sgoInfo;
				$data['data'][$i]['disInfo'] = $disInfo;
				$data['data'][$i]['tradeColumn'] = '详细';
			} elseif ($data['data'][$i]['wtObj'] == 'cardService'){
				$sclList = DB::table('store_cards_log')
							->selectRaw('store_cards_log.*, member_users.muNickName, admin_users.name, store_member_cards.sgName')
							->leftJoin('member_users', 'store_cards_log.muCode', '=', 'member_users.muCode')
							->leftJoin('admin_users', 'store_cards_log.auCode', '=', 'admin_users.auCode')
							->leftJoin('store_member_cards', 'store_cards_log.smcId', '=', 'store_member_cards.smcId')
							->where('store_cards_log.sId', $sId)
							->where('store_cards_log.sclCode', $data['data'][$i]['wtObjId'])
							->get();

				$data['data'][$i]['sclInfo'] = $sclList;
				$data['data'][$i]['tradeColumn'] = '详细';
			} elseif ($data['data'][$i]['wtObj'] == 'recharge' || $data['data'][$i]['wtObj'] == 'consumption'){
				$sgoList = DB::table('store_goods_out')
								->leftJoin('store_goods', 'store_goods_out.sgId', '=', 'store_goods.sgId')
								->leftJoin('member_users', 'store_goods_out.muId', '=', 'member_users.muCode')
								->where('store_goods_out.sId', $sId)
								->where('store_goods_out.sgoOrderId', $data['data'][$i]['wtObjId'])
								->get();
				$data['data'][$i]['sgoList'] = $sgoList;
				$data['data'][$i]['tradeColumn'] = '详细';
			} elseif ($data['data'][$i]['wtObj'] == 'goodsDis'){

				$disInfo = $Distribution->getOrderDis($sId, $data['data'][$i]['wtObjId']);

				$data['data'][$i]['disInfo'] = $disInfo;
				$data['data'][$i]['tradeColumn'] = '详细';
			} elseif ($data['data'][$i]['wtObj'] == 'firstSell'){
				$sgoInfo = DB::table('store_goods_out')
								->leftJoin('store_goods', 'store_goods_out.sgId', '=', 'store_goods.sgId')
								->leftJoin('member_users', 'store_goods_out.muId', '=', 'member_users.muCode')
				                ->leftJoin('admin_users', 'admin_users.auCode', '=', 'store_goods_out.auUserCode')
								->where('sgoId', $data['data'][$i]['wtObjId'])
								->first();

				// $Distribution = new Distribution();
				// $disInfo = $Distribution->getOrderDis($sId, $data['data'][$i]['wtObjId']);

				$data['data'][$i]['sgoInfo'] = $sgoInfo;
				// $data['data'][$i]['disInfo'] = $disInfo;
				$data['data'][$i]['tradeColumn'] = '详细';
			} elseif ($data['data'][$i]['wtObj'] == ''){
				$data['data'][$i]['tradeInfo'] = null;
				$data['data'][$i]['tradeColumn'] = '无';
			} elseif ($data['data'][$i]['wtObj'] == ''){
				$data['data'][$i]['tradeInfo'] = null;
				$data['data'][$i]['tradeColumn'] = '无';
			} elseif ($data['data'][$i]['wtObj'] == ''){
				$data['data'][$i]['tradeInfo'] = null;
				$data['data'][$i]['tradeColumn'] = '无';
			} else {
				$data['data'][$i]['tradeInfo'] = null;
				$data['data'][$i]['tradeColumn'] = '无';
			}
		}

		return $data;
    }

	public function saveBase64Img($base64Img, $folderPath, $fileName){

		if (!is_dir($folderPath)){ //判断目录是否存在 不存在就创建
		  mkdir($folderPath, 0777, true);
		}

		$imageSrc= $folderPath."/". $fileName; //图片名字
		$r = file_put_contents($imageSrc, base64_decode($base64Img));//返回的是字节数
		return $r;
	}
}

?>
